/*
 * @brief
 * @author li yong (DogLee)
 * @email 20162439@qq.com
 * @version 1.0
 * @date 2018-08-02 11:37:49
 */
#include "debug.h"
#include "logmanager.h"
#if defined Q_OS_LINUX
#include "sigactionhandler.h"
#endif

#include <QDateTime>
#include <QFile>
#include <QFileInfo>
#include <QDir>
#include <QMutex>

/**
 * @brief myMessageOutput this function used for handle qdebug message.
 * @param type
 * @param context
 * @param msg
 */
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    static QMutex mutex;
    mutex.lock();

#if 1
    QStringList segments = QString(context.function).split(" ");
    QString func;
    foreach (QString s, segments)
    {
        if (s.contains("("))
        {
            func = s.left(s.indexOf('(')) + "()";
            func = func.split("::").last();
            break;
        }
    }
#else
    QString func = context.function;
#endif

    char buf[128] = {0};
    int offset = 0;
    const char* file = context.file ? context.file : "unknown";
    int fileLength = strlen(file);
    // 让文件名字可以对齐显示,当路径太长时显示子路径和文件名
    if (fileLength >= 30)
        offset = fileLength - 30;
    snprintf(buf, sizeof(buf), "[%.30s:%05u][%.20s]", file + offset, context.line, func.toLocal8Bit().constData());

    QString time = QDateTime::currentDateTime().toString("[yyyy-MM-dd hh:mm:ss-zzz]");
    DebugMessage message;
    message.type = type;
    message.time = time;
    message.context = buf;
    message.content = msg;

    logManager->appendMessage(message);

    mutex.unlock();
}


/**
 * @brief qInstallSigactionHandler 安装自定义信号处理函数
 */
void qInstallSigactionHandler(QString app)
{
#if defined Q_OS_LINUX
    SigactionHandler::install(app);
#endif
}

QString hexData(const unsigned char* pData, int len)
{
    QString str;
    for(int i = 0; i < len; i++)
    {
        str += QString("0x%1, ").arg(pData[i], 2, 16, QLatin1Char('0'));
    }

    return str;
}

void PrintData(const unsigned char* pData, int len, QString cap)
{
    QStringList output;
    output.push_back(cap + ":");
    QString str;
    for(int i = 0; i < len; i++)
    {
        str += QString("0x%1, ").arg(pData[i], 2, 16, QLatin1Char('0'));

        if((i > 0 && (i + 1) % 16 == 0) || i == len - 1)
        {
            output.push_back(str);
            str.clear();
        }
    }

    foreach (QString s, output)
    {
        printf("%s\n", qPrintable(s));
    }
    fflush(stdout);
}

void PrintData(const char* pData, int len, QString cap)
{
    unsigned char* p = (unsigned char*)pData;
    PrintData(p, len, cap);
}

void PrintData(const QByteArray &data, QString cap)
{
    const unsigned char* p = (const unsigned char*)data.constData();
    PrintData(p, data.size(), cap);
}

QString toString(const quint64 tm)
{
    return toString(QDateTime::fromSecsSinceEpoch(tm));
}

QString toString(const QDateTime &dateTime)
{
    return dateTime.toString("yyyy-MM-dd hh:mm:ss");
}
